
package com.yunhoo.contract.bean;

import com.yunhoo.contract.model.ContractDocument;
import com.yunhoo.cqq.model.DocumentType;
import com.yunhoo.cqq.model.TempFile;
import com.yunhoo.sys.util.common.FacesUtils;
import com.yunhoo.sys.util.common.LoginParam;
import com.yunhoo.sys.util.common.ToolKit;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import org.richfaces.event.FileUploadEvent;
import org.richfaces.model.UploadedFile;

@ManagedBean(name = "fileUploadBean")
@SessionScoped
public class FileUploadBean {

    private List<TempFile> files = new ArrayList<TempFile>();
    private List<ContractDocument> uploadedDocumentList = new ArrayList<ContractDocument>();//当前已上传附件列表
    private int maxAmount;//当前允许 最大上传文件数
    private long maxSize;//当前允许 最大上传文件大小

    public void init() {
        files = new ArrayList<TempFile>();
        uploadedDocumentList = new ArrayList<ContractDocument>();
    }

    public void initParam(int maxAmount, Double maxSize) {
        this.maxAmount = maxAmount;
        this.maxSize = maxSize.longValue();
    }

    public int getSize() {
        if (getFiles().size() > 0) {
            return getFiles().size();
        } else {
            return 0;
        }
    }

    public void paint(OutputStream stream, Object object) throws IOException {
        stream.write(getFiles().get((Integer) object).getData());
    }

    private long curSize() {
        long len = 0l;
        for (TempFile temp : files) {
            len += temp.getLength();
        }
        return len;
    }

    public void listener(FileUploadEvent event) throws Exception {
        if (!(uploadedDocumentList.size() < maxAmount)) {
            ToolKit.msgs_err(FacesContext.getCurrentInstance(), "docUploadArea", "已达上传数上限");
            return;
        }
        //做表单验证
        try {
            UploadedFile item = event.getUploadedFile();
            if ((curSize() + item.getSize()) > maxSize) {
                ToolKit.msgs_err("文件大小已达上限");
                return;
            }
            String uploadDirectory = FacesContext.getCurrentInstance().getExternalContext().getInitParameter("uploadResources");//获取上传文件存储路径-web.xml
            String fileName = item.getName().substring(item.getName().lastIndexOf("\\") + 1);//文件名
            String saveFileName = getRandomString(fileName);
            String filepath = uploadDirectory + "\\" + saveFileName.substring(0, saveFileName.lastIndexOf(".")) + "\\";
            HttpServletRequest request = FacesUtils.getServletRequest();

            String url = uploadDirectory + "\\" + saveFileName.substring(0, saveFileName.lastIndexOf(".")) + "\\" + fileName;

            //创建File对象,将上传的文件保存到指定文件夹下
            System.out.println(filepath);
            File file1 = new File(filepath);
            if (file1.exists()) {
            } else {
                file1.mkdirs();
            }
            File file = new File(filepath, fileName + "");

            //将该数据流写入到指定文件中
            FileOutputStream out = new FileOutputStream(file);
            out.write(item.getData());

            //用于页面回显相关信息
            TempFile tempFile = new TempFile();
            tempFile.setLength(item.getData().length);
            tempFile.setName(fileName);
            tempFile.setData(item.getData());
            files.add(tempFile);

            //得到所有能够访问该文件的人员
            //根据名字遍历结束，得到所有具备查看该文档权限的人员集合userList
            //将文档信息插入数据库，首先包装文档信息
            ContractDocument documentTemp = new ContractDocument();
            documentTemp.setTitle(fileName);
            documentTemp.setDescription(fileName);
            documentTemp.setDocSize(CountFileSize(tempFile.getLength()));
            documentTemp.setUploadDate(new Date());
            documentTemp.setUserName(LoginParam.getPer().getCpsn_number());//上传的人员
            documentTemp.setUrl(url);

            uploadedDocumentList.add(documentTemp);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String CountFileSize(long size) {
        if (size < 1024l) {
            return size + "B";
        } else if (size < (1024l * 1024l)) {
            return Math.round((size * 100 >> 10)) / 100.00 + "KB";
        } else if (size < (1024l * 1024l * 1024l)) {
            return (Math.round((size * 100 >> 20)) / 100.00) + "MB";
        } else {
            return Math.round((size * 100 >> 30)) / 100.00 + "GB";
        }
    }

    public String getRandomString(String fileName) {
        if (fileName.lastIndexOf(".") != -1) {
            return UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
        } else {
            return UUID.randomUUID().toString() + fileName;
        }
    }

    public String clearUploadData() {
        files.clear();
        uploadedDocumentList.clear();
        return null;
    }

    public long getTimeStamp() {
        return System.currentTimeMillis();
    }

    public List<TempFile> getFiles() {
        return files;
    }

    public void setFiles(ArrayList<TempFile> files) {
        this.files = files;
    }

    public List<ContractDocument> getUploadedDocumentList() {
        return uploadedDocumentList;
    }

    public void setUploadedDocumentList(List<ContractDocument> uploadedDocumentList) {
        this.uploadedDocumentList = uploadedDocumentList;
    }

    public int getMaxAmount() {
        return maxAmount;
    }

    public void setMaxAmount(int maxAmount) {
        this.maxAmount = maxAmount;
    }
}
